<?php
namespace Admin\Controller;

class BannerController extends PublicController
{
    function _initialize()
    {
        parent::_initialize();
    }

    //列表
    public function index()
    {
        $id = I('get.id');
        $where['cid'] = $id;
        $result = M('img')->where($where)->select();
        $this->assign("banner", $result);
        $this->assign("PATH", PATH);
        $this->display();
    }

    public function edit()
    {
        //根据id查询
        $id = I('get.id');
        if ($id) {
            $result = M("Banner")->where("id = '$id'")->find();
        } else {
            $result = '';
        }
        $this->assign("bannerList", $result);
        $this->display();
    }

    //添加、修改
    public function addbanner()
    {
        $data = I();
        $id = $data['id'];
        //是否有图片上传
        if ($_FILES['pic_url']['name'] !== '') {
            $upload = $this->uploadOne($_FILES['pic_url']);
            $data['pic_url'] = ltrim($upload[savepath], ".") . $upload[savename];
        } else {
            $data['pic_url'] = I("post.pic_url");
        }

        if ($id) {//修改
            $data['add_time'] = $data['save_time'] = time();
            $result = M("Banner")->where("id = '$id'")->save($data);

            if ($result !== false) {
                $this->success("操作成功", "Banner/index");
            } else {
                $this->error("操作失败");
            }
        } else {//新增
            $data['save_time'] = time();
            $result = M("Banner")->add($data);
            if ($result !== false) {
                $this->success("操作成功", "Banner/index");
            } else {
                $this->error("操作失败");
            }
        }
    }

    //修改用的ajax，给前台提供数据
    public function getbanner()
    {
        $id = I('id');
        $result = M("Banner")->find($id);
        echo json_encode($result);
    }

    //删除图片
    public function delbanner()
    {
        $id = I("get.id");
        $result = M("img")->where(array(
            'id' => $id
        ))->delete();
        if ($result !== false) {
            $this->success("删除成功");
        } else {
            $this->error("操作失败");
        }
    }
}
